package com.hmall.item.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constatnts.MqConstants;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.InsertItem;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.RequestParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService{

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemService itemService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageDTO<Item> findAll(RequestParams requestParams) {
        Page<Item> result = itemService.page(new Page<>(requestParams.getPage(), requestParams.getSize()));
        return new PageDTO<>(result.getTotal(),result.getRecords());
    }

    @Override
    public Item findById(Long id) {
        return itemMapper.selectById(id);
    }

    @Override
    public void insertItem(Item item) {
        itemMapper.insert(item);
        //发送mq消息 交换机名字，路由key，信息
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,item.getId());
        log.info("插入成功");
    }

    @Override
    public void changeStatus(Long id, Integer status) {
        Item item = itemMapper.selectById(id);
        item.setStatus(status);
        itemMapper.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,item.getId());
    }

    @Override
    public void updateItem(Item item) {
        itemMapper.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_KEY,item.getId());
    }
}
